//
//  ICChangeMasterController.m
//  ICome
//
//  Created by ENN on 16/6/6.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICChangeMasterController.h"
#import "ICDetailSearchController.h"
#import "ICContactListCell.h"
#import "UIImage+AvatarGeneration.h"
#import "ICHeaderFile.h"
@interface ICChangeMasterController ()<UISearchControllerDelegate,UISearchBarDelegate,UITableViewDelegate, UITableViewDataSource, DetailSearchDelegate>

@property (nonatomic, strong) ICBaseSearchViewController *searchController;

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation ICChangeMasterController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    for (int i = 0; i < self.users.count; i ++) {
        ICUser *user = self.users[i];
        if ([user.eId isEqualToString:[ICUser currentUser].eId]) {
            [self.users removeObjectAtIndex:i];
            break;
        }
    }
    
    [self setupUI];
}

- (void)setupUI
{
    self.title = @"成员";
    ICDetailSearchController *searchVC   = [[ICDetailSearchController alloc] init];
    searchVC.delegate = self;
    searchVC.gId = self.gId;
    searchVC.gId                         = self.gId;
    
    ICBaseSearchViewController *searchController = [[ICBaseSearchViewController alloc] initWithSearchResultsController:searchVC];
    self.tableView.tableHeaderView = searchController.searchBar;
    searchController.placeholder = @"搜索";
    searchController.delegate = self;
    searchController.searchBar.delegate  = self;
    searchController.searchResultsUpdater = searchVC;
    _searchController = searchController;
    self.definesPresentationContext = YES;
    
    self.tableView.frame  = CGRectMake(0,0, self.view.width, self.view.height-self.tabBarController.tabBar.height);
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}



#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.users.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 55.0f * Level;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *res = @"cell";
    ICContactListCell *cell = [tableView dequeueReusableCellWithIdentifier:res];
    if (!cell) {
        cell = [[ICContactListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:res];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ICUser *model = [self.users objectAtIndex:indexPath.row];
    
    
    cell.titleLabel.text = model.eName;
    NSString *URL = [ICTools getMinImageURL:(model.photoId)];
    [UIImage addAvatariamgeView:cell.headImageView withUrlStr:URL witheId:model.eId withName:model.eName];
//    [cell.headImageView sd_setImageWithURL:[NSURL URLWithString:URL] placeholderImage:[UIImage imageNamed:@"App_personal_headimg"]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ICUser *user = self.users[indexPath.row];
    if ([user.eId isEqualToString:[ICUser currentUser].eId]) {
        [MBProgressHUD showSuccess:@"你就是群主!"];
        return;
    }
    NSString *message = [NSString stringWithFormat:@"确定选择%@为新群主，你将自动放弃群主身份。",user.eName];
    UIAlertController *alerController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self changeMaster:user];
    }];
    [alerController addAction:cancel];
    [alerController addAction:okAction];
    [self presentViewController:alerController animated:NO completion:nil];
}

- (void)detailSearch:(NSString *)eId
{
    
    ICUser *user;
    //=  self.users[indexPath.row];
    for(ICUser *user1 in self.users )
    {
        if([eId isEqualToString:user1.eId])
        {
            user = user1;
        }
    }
    
  
    
    if ([user.eId isEqualToString:[ICUser currentUser].eId] || [eId isEqualToString:[ICUser currentUser].eId]) {
        [MBProgressHUD showSuccess:@"你就是群主!"];
        return;
    }
    NSString *message = [NSString stringWithFormat:@"确定选择%@为新群主，你将自动放弃群主身份。",user.eName];
    UIAlertController *alerController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self changeMaster:user];
    }];
    [alerController addAction:cancel];
    [alerController addAction:okAction];
    [self presentViewController:alerController animated:NO completion:nil];
}

- (void)changeMaster:(ICUser *)user
{
    
    NSDictionary *param = @{
                            @"gId":self.gId,
                            @"eId":user.eId
                            };
    [MBProgressHUD showMessage:@"正在转让..." toView:self.view];
    [[ICSocketRequestManager sharedInstance] changeMasterWithObject:param Success:^(id response) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showSuccess:@"转让成功"];
        [ICMessageDatabase changeGroupMaster:self.gId isMaster:NO];
        if ([self.delegate respondsToSelector:@selector(changeMaster)]) {
            [self.delegate changeMaster];
        }
        [self.navigationController popViewControllerAnimated:YES];
    } Failure:^(NSError *error, id other) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"转让失败,请重试"];
    }];
}



#pragma mark - searchBarDelegate

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:YES];
    for(UIView *view in  [[[searchBar subviews] objectAtIndex:0] subviews]) {
        if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) {
            UIButton * cancel =(UIButton *)view;
            [cancel setTitle:@"取消" forState:UIControlStateNormal];
            [cancel setTitleColor:ICSEARCHCANCELCOLOR forState:UIControlStateNormal];
        }
    }
}



- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, App_Frame_Width, APP_Frame_Height-64) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

@end
